﻿using iTextSharp.text.pdf;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
using Tools.Helper;

namespace Tools
{
    public partial class MicrosoftCalendarOld : Base
    {
        /// <summary>
        /// 中国北京时区
        /// </summary>
        string timezone = "China Standard Time";

        /// <summary>
        /// 工作日报日历ID
        /// </summary>
        string ribao = "AQMkADAwATY3ZmYAZS1hOGQ5LWI1NjEtMDACLTAwCgBGAAAD63Q7MReF3U_07sh48tkOlAcA2ME1sP4OHkG8uWM1VkagLgAAAgEGAAAA2ME1sP4OHkG8uWM1VkagLgADaKnBpQAAAA==";

        public MicrosoftCalendarOld()
        {
            InitializeComponent();
            base.SetDefaultLocation();

            DataBindTime(DateTime.Now.ToString("HH:00"));
            GetLogAsync(DateTime.Now);
        }

        #region 添加事件

        private async void Btn_add_ClickAsync(object sender, EventArgs e)//添加事件
        {
            var url = $"https://graph.microsoft.com/beta/me/calendars/{ribao}/events";
            var isAllDay = false;
            var start = Picker_Start.Value.ToShortDateString() + " " + cob_start.Text;
            var end = Picker_End.Value.ToShortDateString() + " " + cob_end.Text;

            if (chb_all.Checked)
            {
                var time = DateTime.Now.ToShortDateString();
                isAllDay = true;
                end = start = DateTime.Now.ToShortDateString();
            }

            var obj = new
            {
                isAllDay = isAllDay,
                isReminderOn = false,//不提醒
                subject = txt_title.Text,
                body = new
                {
                    contentType = "text",
                    content = ""
                },
                start = new
                {
                    dateTime = start,
                    timeZone = timezone
                },
                end = new
                {
                    dateTime = end,
                    timeZone = timezone
                },
                location = new
                {
                    displayName = "中国辽宁省沈阳市"
                },
                allowNewTimeProposals = true,
                transactionId = Guid.NewGuid()
            };
            MicrosoftToken.HttpRequest(url, JsonConvert.SerializeObject(obj));

            GetLogAsync(DateTime.Now);
            txt_title.Text = "";
            MessageBox.Show("添加事件成功!");
        }
        #endregion

        #region 获取事件列表

        /// <summary>
        /// 获取事件
        /// </summary>
        /// <param name="time"></param>
        /// <returns></returns>
        private async void GetLogAsync(DateTime time)
        {
            await MicrosoftToken.SetTokenAsync();
            var select = $"subject,body,bodyPreview,organizer,attendees,start,end,location";
            var filter = $"start/dateTime ge '{time.ToString("yyyy-MM-dd")}' and end/dateTime lt '{time.AddDays(1).ToString("yyyy-MM-dd")}'";
            var orderby = $"start/dateTime";
            var url = $"https://graph.microsoft.com/beta/me/calendars/{ribao}/events?$filter={filter}&$orderby={orderby}&$select={select}&$top=999";
            var res = MicrosoftToken.HttpRequest(url, "", "get");
            var list = JsonConvert.DeserializeObject<dynamic>(res).value;

            var events = new List<Calendar.CalenderModel>();
            foreach (var item in list)
            {
                events.Add(new Calendar.CalenderModel() { Title = item["subject"].ToString(), Start = Convert.ToDateTime(item["start"]["dateTime"].ToString()), End = Convert.ToDateTime(item["end"]["dateTime"].ToString()) });
            }

            var timeStr = DateTime.Now.ToString("HH:mm");
            var str = base.GetEevents(events, out timeStr);
            txt_log.Text = str;
            cob_start.SelectedItem = timeStr;
        }
        #endregion

        #region 选择开始时间

        private void cob_start_SelectedIndexChanged(object sender, EventArgs e)
        {
            cob_end.SelectedItem = Convert.ToDateTime(Picker_Start.Value.ToShortDateString() + " " + cob_start.Text).AddHours(1).ToString("HH:mm");

            var flag = false;
            cob_end.Items.Clear();

            foreach (var item in time1)
            {
                if (item == cob_start.Text)
                {
                    flag = true;
                }
                if (flag)
                {
                    cob_end.Items.Add(item);
                }
            }
            cob_end.SelectedItem = Convert.ToDateTime("2018-08-16 " + cob_start.Text).AddHours(1).ToString("HH:mm");
        }
        #endregion

        #region 明日计划

        private void chb_tomorrow_CheckedChanged(object sender, EventArgs e)
        {
            if (chb_tomorrow.Checked)
            {
                txt_title.Text = "1.计划\r\n2.计划\r\n3.计划";
                cob_start.Text = "17:30";
                cob_end.Text = "17:30";
            }
            else
            {
                txt_log.Text = "";
            }
        }
        #endregion

        #region 其它事件

        /// <summary>
        /// 时间 格式 HH:00
        /// </summary>
        /// <param name="dateTimeStr"></param>
        public void DataBindTime(string dateTimeStr)
        {
            cob_start.DataSource = time;
            cob_start.SelectedItem = dateTimeStr;
        }

        private void btn_select_Click(object sender, EventArgs e)
        {
            GetLogAsync(DateTime.Now);
        }

        private void btn_month_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("https://outlook.live.com/calendar/0/view/month");
        }

        private void btn_day_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("https://outlook.live.com/calendar/0/view/day");
        }

        private void monthCalendar1_DateChanged(object sender, DateRangeEventArgs e)
        {
            GetLogAsync(this.monthCalendar1.SelectionEnd);
        }
        #endregion
    }
}
